var inviteOK=false;
var ws;
var localhost = true;
var enviar = "";
var activarenvio = false;
var sendto="";
var friends;
var ocupado=false;
var loginsuccess=false;
var signin=false;
var login=false;
var websocketopen=false;
var ipserv="localhost"; 
var port=":8887"; 
var idSesion="";
var primeravez=true;

/*
 * Patrick
 * WEBSOCKET COMUNICATION WITH ONE CHAT
 */
function ChatWith(name,istext){	
	ocupado=true;
	name =  namereturn(name);
	$('#Me').html($('#name').val());//escribimos mi nombre
	if(!istext){		
		inviteOK=false;
	}
	//proceso de llamada INVITE
	if(!inviteOK){	
		ws.send("INVITE#"+name+"#FROM#"+$('#name').val());	//enviamos invite
		$('#nameuser').html('Calling...');					//escribimos llamando hasta que salga	
		PAINT(2);										//pintamos chat
	}
	
	//eperar a INVITE-OK
	if(inviteOK){	//dibujamos la parte de colgar del usuario
		var javascriptuser="";
		var html='<ul data-role="listview" data-theme="e" id="userlist">';		
		html=html+'<li id="'+name+'" onclick="javascript:ChatEnd('+name+');"><a>'+name+'</a>'+
		'<a onclick="javascript:ChatEnd('+name+');" data-icon="callout"  data-rel="dialog" data-transition="slideup" data-theme="c" ></a></li>';
		javascriptuser=javascriptuser+'$("'+'#'+name+' a"'+').click(function(e){'+
		'ChatEnd("'+name+'");'+
		'});';	
		
		
		
		sendto="FROM#"+$('#name').val()+"#TO#"+name;		
		html=html+'</ul>';
		
		$('#nameuser').html(html);
		if(navigator.userAgent.toString().indexOf("Firefox", 0)!=-1){
			$('script').remove();
			var etiquetascript = document.createElement("script");
			document.getElementsByTagName("head")[0].appendChild(etiquetascript);
			etiquetascript.text=javascriptuser;	
		}
		if(navigator.userAgent.toString().indexOf("iPad", 0)!=-1){
			$('script').remove();
			javascriptnew=javascriptuser.replace(/click\(/g,'bind("tap",');
			var etiquetascript = document.createElement("script");
			document.getElementsByTagName("head")[0].appendChild(etiquetascript);
			etiquetascript.text=javascriptnew;	
		}
		
		$("#nameuser ul").listview();		
		inviteOk=false;	
		
		PAINT(2);										//pintamos chat
	}
				
}

/*
 * Patrick
 * WEBSOCKET MAKE OR DELETE FRIENDS 
 */
function makefriend(name,proces){
	name =  namereturn(name);
	if(proces){//hacer amigo
		ws.send("FRIENDWITH#"+name+"#FROM#"+$('#name').val());
	}else{//quitar amigo
		ws.send("UNFRWITH#"+name+"#FROM#"+$('#name').val());
	}
}


/*
 * Patrick
 * WEBSOCKET GETNODETYPE for HTMLCOllection
 */
function getNodeType(node){
    return node.constructor.name;
}

/*
 * Patrick
 * WEBSOCKET COMUNICATION FiNISH ONE CHAT
 */
function ChatEnd(name){
	ocupado=false;
	name =  namereturn(name);
	//alert("Not Implemented yet");	
	ws.send("BYE#"+name+"#FROM#"+$('#name').val());	
	listview_make("friends",friends,true);
	PAINT(3);							//volvemos a amigos
	inviteOK=false;
	
}


/* Patrick
 * INFO LOG
 */
function log(text, id) {
	//$("#log").append( (new Date).getTime() + ": " + text);
	//$("#" + id).append(text);
	var val = $("#"+id).val(); //store the value of the element
   // $("#"+id).val(''); //clear the value of the element
    $("#"+id).val(val+text); //set that value back. 				
}

function begin_websockets(){
	//abrimos websockets 	
		if(window.MozWebSocket) {
			ws = new MozWebSocket("ws://"+ipserv+port);
			websocketopen=true;
		}else{
			ws = new WebSocket("ws://"+ipserv+port);
			websocketopen=true;
		}
	
	ws.onopen = function() {
		log("[WebSocket#onopen]\n", "loginfo");
		
	};
	
	ws.onmessage = function(e) {
		log(e.data+"\n","loginfo");							
		if (e.data.length < 2) {
			if (e.data.indexOf("websocket") != -1) {
				log(e.data + "\n", "loginfo");
			} else {
				log(e.data, "log");
			}
		} else if ((e.data.indexOf("FRIENDSONLINE#") != -1)&&(loginsuccess)) {	//USUARIOS ONLINE
			//modificamos listview para ver users online			
			if(!ocupado){
			listview_make("users",e.data,false);								
			listview_make("friends",friends,true);
			}else{
				listview_make("users",e.data,false);								
				listview_make("friends",friends,false);	
			}
			} else if ((e.data == "keycode<8>")&&(loginsuccess)) {			//RECIBIMOS TECLA DE BORRADO
			//borrar                		
			$("#log").html(
					$("#log").val().substring(0,
							$("#log").val().length - 1));
			}else if ((e.data.indexOf("INVITE#") != -1)&&(loginsuccess)) {	//recibimos INVITE
				//Llega una llamada, INVITE
				fragmentoTexto = e.data.split('#');
				inviteOK=true;									
				Show_Popup(fragmentoTexto[3]);//pop up de llamando
				//ChatWith(fragmentoTexto[3],true);//empezamos chat
				
			}else if ((e.data.indexOf("INVITE-OK#") != -1)&&(loginsuccess)) {//recibimos INVITE-OK
				//Llega un ok de llamada, INVITE
				fragmentoTexto = e.data.split('#');
				inviteOK=true;
				ChatWith(fragmentoTexto[3],true);//empezamos chat
				
				
			}else if ((e.data.indexOf("FRIENDS#") != -1)&&(loginsuccess)) {//recibimos INVITE-OK
				//Llega la petici�n de mis amigos									
				//modificamos listview para ver amigos online									
				listview_make("friends",e.data,true);
				friends=e.data;									
				
			}else if (e.data.indexOf("USERLOGIN#") != -1) {//recibimos RESPUESTA LOGIN
				fragmentoTexto = e.data.split('#');									
				if(fragmentoTexto[1]=="TRUE"){
					loginsuccess = true;
					ws.send("FRIENDSONLINE#");	//pedimos usuarios		
					ws.send("FRIENDS#"+$('#name').val());//pedimos amigos
				}else{
					$('#loginresult').html('User and password not valid, please try again.');
					setTimeout("$('#loginresult').html('')",1000);
				}									
				
			}else if (e.data.indexOf("SIGNIN#") != -1) {//recibimos RESPUESTA SIGNIN
				fragmentoTexto = e.data.split('#');									
					loginsuccess = false;
					signin=false;
					$('#registerresult').html(fragmentoTexto[1]);																	
				
			}else if ((e.data.indexOf("SEARCH#") != -1)&&(loginsuccess)) {//recibimos SEARCH
				//Llega la petici�n de busqueda									
				//modificamos listview para ver respuesta
				if(e.data=="SEARCH#"){
					$('#resultsearch').html('No he ha encontrado resultado');
					setTimeout("$('#resultsearch').html('')",1000);
				}else{
				listview_make("resultsearch",e.data,false);	
				}
				
			}else if ((e.data.indexOf("BYE#") != -1)&&(loginsuccess)) {//recibimos BYE
				//Llega un ack de llamada, INVITE
				ocupado=false;
				fragmentoTexto = e.data.split('#');
				listview_make("friends",friends,true);
				//hacemos desaparecer el chat y volvemos a la parte principal
				PAINT(3,"");
				inviteOK=false;									
				
			}else if ((e.data.indexOf("MESSAGE#") != -1)&&(loginsuccess)) {	//recibimos Mensaje
				//Llega una mensaje, MESAGE
				fragmentoTexto = e.data.split('#');									
				if(fragmentoTexto[1]=="keycode<8>"){
					$("#log").val(
							$("#log").val().substring(0,
									$("#log").val().length - 1));
				}else{
				log(fragmentoTexto[1], "log");//pintamos por pantalla el mensaje
				}
				$('#log').scrollTop($('#log')[0].scrollHeight - $('#log').height());
				//$('#log').scrollTop=$('#log').scrollHeight;
			}else if ((e.data.indexOf("IDSESION")!=-1)){
				fragmentoTexto = e.data.split('#');	
				idSesion = fragmentoTexto[1];
			}

	};
	ws.onclose = function() {		
		log("[WebSocket#onclose]\n");
		$('#connect').removeAttr('disabled');
		$('#disconnect').removeAttr('disabled');							
	};
		
}


$(document).ready(function() {
	
	/*ws.onopen
	 * Patrick
	 * WEBSOCKET SIGN IN click
	 */
	$('#signin').click(function(e) {
		//enviamos petici�n	
		
		if(($("#password2").val()==$("#password1").val())&&($("#password2").val().length>7)&&($("#password1").val().length>7)){
			ws.send("SIGNIN#"+$('#name1').val()+"#PASS#"+$("#password2").val());
			$('#name').val($('#name1').val());
			}else{
				$('#registerresult').html("Passwords don't match, or size is less than 8 characters");
				setTimeout($('#registerresult').html(''),1000);
			}		
		});
	
	/*ws.onopen
	 * Patrick
	 * WedSocket Connect Click, (Log IN)
	 */
	
	$('#connect').click(function(e) {
		//enviamos peticion			
		ws.send("idUsuario#" + $('#name').val()+"#PASS#"+$('#password').val());//hacemos login
		/*if(loginsuccess){
		PAINT(1);	//vamos a amigos
		$('#connect').attr('disabled', 'disabled');						
		$('#disconnect').removeAttr('disabled');
		}	*/	
	});	
	
	/*
	 * Patrick Websockects Events
	 */	
	begin_websockets();			
	
	//Comprobamos compatibilidad
			if (!window.WebSocket && !window.MozWebSocket )  {
				log("WebSocket not natively supported, falling back to Flash","log");
				WEB_SOCKET_SWF_LOCATION = "WebSocketMain.swf";
				WEB_SOCKET_DEBUG = true;
				$("head").append('<script	src="js/web_socket.js"></script>');
			}else if(window.MozWebSocket) {
				log("Using browser's native WebSocket Firefox 6.0 implementation\n","loginfo");				
			}else {
				log("Using browser's native WebSocket implementation\n","loginfo");				
			}
			
			
			//iniciamos pantalla con menu
			menu_on();
			$('#chat').css({'display':'none'});
			$("#friendsup").css({'display':'none'});
			$("#usersup").css({'display':'none'});
			$("#loginfo").scrollTop(50000);				

			/*
			 * Patrick
			 * WEBSOCKET DISCONNECT
			 */
			$('.menu3').click(function(e) {	
				if(ws){
				ws.send("SOUT#"+$('#name').val());	//enviamos cerrar sesion
				}
				PAINT(4);							//pintamos lo que toca
				if (ws) {
					ws.close();
					ws = null;
					begin_websockets();
				}				
			});
			/*
			 * Patrick
			 * WEBSOCKET FRIENDS MENU
			 */
			$('.menu1').click(function(e) {		
				if(loginsuccess){
				PAINT(1);		
				}//volvemos a amigos						
			});
			/*
			 * Patrick
			 * WEBSOCKET REGISTER MENU
			 */
			$('.menu5').click(function(e) {					
				PAINT(6);		//vamos a registrarnos										
			});			
			/*
			 * Patrick
			 * WEBSOCKET OPTIONS MENU
			 */
			$('.menu4').click(function(e) {					
				PAINT(7);											
			});
			
			$('#logother').keydown(function(e) {
				$('#logother').scrollTop=$('#logother').scrollHeight;
				$('#log').scrollTop=$('#log').scrollHeight;
				var code = 0;				
				if (!e)
					var e = window.event;
				if (e.keyCode)	code = e.keyCode;
				else if (e.which)  code = e.which;
								
				if (ws) {					
					if (code == 8) {
						enviar = "keycode<8>";
						ws.send("MESSAGE#"+enviar+"#"+sendto);
					}					
					
				}
				$("#logother").focus();
				var val = $("#logother").val(); //store the value of the element
		        $("#logother").val(''); //clear the value of the element
		        $("#logother").val(val); //set that value back.			
			        
			});
			/* Patrick
			 * CHAT KEY DETECT
			 */
			$('#logother').keypress(function(e) {	
				$('#logother').scrollTop=$('#logother').scrollHeight;
				$('#log').scrollTop=$('#log').scrollHeight;
				var code = 0;			
				if (!e)
					var e = window.event;
				if (e.keyCode)
					code = e.keyCode;
				else if (e.which)
					code = e.which;
				enviar = String.fromCharCode(code);					
				if (ws) {					
					ws.send("MESSAGE#"+enviar+"#"+sendto);					
					$("#logother").focus();
					//monitorizamos el cursor
				          var val = $("#logother").val(); //store the value of the element
				          $("#logother").val(''); //clear the value of the element
				          $("#logother").val(val); //set that value back. 					 
				}
			});
			
			$('#logother').click(function(){
				 var val = $("#logother").val(); //store the value of the element
		          $("#logother").val(''); //clear the value of the element
		          $("#logother").val(val); //set that value back. 
			});
			
			//control sobre el otro log
			$('#log').click(function(){
				 $("#logother").focus();		          
			});
			$('#log').keypress(function(e) {
				var val = $("#log").val(); //store the value of the element
		          $("#log").val(''); //clear the value of the element
		          $("#log").val(val); //set that value back. 
				$("#logother").focus();
			});
			$('#log').keydown(function(e) {
				var val = $("#log").val(); //store the value of the element
		          $("#log").val(''); //clear the value of the element
		          $("#log").val(val); //set that value back. 
				$("#logother").focus();
			});
		});





/* Patrick
 * listview for friends
 */
var usersonline="";
var imgonline;
var imgoffline;
var online;

function listview_make(id,frangmento,paint){
	if(id=="users"){
		usersonline="";//actualizamos el registro
	}
	var icon="plus";
	var proceso=true;	
	var javascriptnew="";
	imgoffline="";
	imgonline="";	
	if(id=="friends"){
		icon="call";	//icono que ponemos en pantalla
		proceso=false;	
		online=usersonline.split('#');		
	}	
	fragmentoTexto = frangmento.split('#');
	
	var html='<div style="padding-top: 3%; " ><ul data-role="listview" data-theme="e" id="userlist">';
	for (x = 1; x <= fragmentoTexto.length-2; x++) {
		if(id=="users"){
			usersonline=usersonline+fragmentoTexto[x]+"#";
		}
		if(!(fragmentoTexto[x]==$('#name').val())){
			if(id=="friends"){
				if(usersonline.indexOf(fragmentoTexto[x], 0)!=-1){
					//imgonline='<img src="css/verde.png"/>';
					imgonline='<p class="online">Online</p>';
					imgoffline="";
					html=html+'<li id="'+fragmentoTexto[x].replace(" ","")+'fr"  data-icon="false" ><a>'+''+fragmentoTexto[x]+imgonline+imgoffline+'</a>'
					+'<a class="chatwithx" onclick="javascript:ChatWith('+fragmentoTexto[x].replace(" ","")+'fr,false);" data-icon='+icon+'  data-rel="dialog" data-transition="slideup" title="FRiend" data-theme="c" ></a></li>';
					javascriptnew=javascriptnew+'$("'+'#'+fragmentoTexto[x].replace(" ","")+'fr a"'+').click(function(e){'+
					'ChatWith("'+fragmentoTexto[x].replace(" ","")+'",false);'+
				'});';	
					//+'<a onclick="javascript:makefriend('+fragmentoTexto[x]+'fr,'+proceso+');" data-icon='+icon+'  data-rel="dialog" data-transition="slideup" title="FRiend" data-theme="c" ></a></li>';
					
				}else{
					imgonline="";
					imgoffline='<p class="offline">Offline</p>';
					//imgoffline='<img src="css/rojo.png" />';
					html=html+'<li id="'+fragmentoTexto[x].replace(" ","")+'fr"  data-icon="false"><a>'+''+fragmentoTexto[x]+imgonline+imgoffline+'</a>'
					+'</li>';
					
				}
			} else if(id=="resultsearch"){
				icon="makefriend";
				html=html+'<li id="'+fragmentoTexto[x].replace(" ","")+'"  data-icon="false"><a>'+''+fragmentoTexto[x]+'</a>'
				+'<a class="FRiend" onclick="javascript:makefriend('+fragmentoTexto[x].replace(" ","")+',true);"  data-icon='+icon+'  data-rel="dialog" data-transition="slideup" data-theme="c"></a></li>';
				javascriptnew=javascriptnew+'$("'+'#'+fragmentoTexto[x].replace(" ","")+' a"'+').click(function(e){'+
					'makefriend("'+fragmentoTexto[x].replace(" ","")+'",true);'+
				'});';			
				
			}else if(id=="rmfriends"){
				icon="makefriend";				
				html=html+'<li id="'+fragmentoTexto[x].replace(" ","")+'"  data-icon="false"  ><a>'+''+fragmentoTexto[x]+'</a>'
				+'<a class="FRiend" href="javascript:makefriend('+fragmentoTexto[x].replace(" ","")+',false); return true;"  data-icon="unmakefriend"  data-rel="dialog" data-transition="slideup" data-theme="c"></a></li>';
				javascriptnew=javascriptnew+'$("'+'#'+fragmentoTexto[x].replace(" ","")+' a"'+').click(function(e){'+
					'makefriend("'+fragmentoTexto[x].replace(" ","")+'",false);'+
				'});';			
				
			}else{
			
		html=html+'<li id="'+fragmentoTexto[x]+'"  data-icon="false"><a onclick="javascript:ChatWith('+fragmentoTexto[x]+',false);">'+''+fragmentoTexto[x]+imgonline+imgoffline+'</a>'
		+'<a onclick="javascript:makefriend('+fragmentoTexto[x]+','+proceso+');" data-icon='+icon+'  data-rel="dialog" data-transition="slideup" title="FRiend" data-theme="c"></a></li>';
						
			}		
		}		
	}
	html=html+'</ul></div>';
	$("#"+id+"").html(html);
	//$('script').remove();	
	if(javascriptnew!=""){
	if(navigator.userAgent.toString().indexOf("Firefox", 0)!=-1){
		$('script').remove();
		//javascriptnew=javascriptnew.replace(/click(/g,'bind("tap",');
		var etiquetascript = document.createElement("script");
		document.getElementsByTagName("head")[0].appendChild(etiquetascript);
		etiquetascript.text=javascriptnew;	
	}
	if(navigator.userAgent.toString().indexOf("iPad", 0)!=-1){
		$('script').remove();
		javascriptnew=javascriptnew.replace(/click\(/g,'bind("tap",');
		var etiquetascript = document.createElement("script");
		document.getElementsByTagName("head")[0].appendChild(etiquetascript);
		etiquetascript.text=javascriptnew;	
	}
	}
	
	if(id=="resultsearch"){
		PAINT(5); //dibujamos
	}
	if(paint){
	PAINT(1);
	}	
	
}


/* Patrick
 * Pintamos o no pantalla segun casos
 */
function PAINT(num){
	
	switch(num){
	case 1: //pintar en pantalla la lista de amigos con boton search
		ocupado=false;
		$('#rmfriends').css({'display':'none'});
		$('#login').fadeOut('fast');
		$(".menu3").html('<p><a class="amenu" >Logout</a>'+'</p>');
		$(".menu3 a").css({'color':'#BDBDBD','cursor':'pointer'});		
		setTimeout('$("#friends").css({"display":"block"});', 2000);
		//$("#friends").hide();	//escondemos
		if(primeravez){
		$("#friends ul").hide();	//escondemos
		}
		$(".logusers").css({'display':'block'});	
		$("#friends ul").listview();
		$("#friends ul").css({'padding': '.8em 3px .5em 35px'});	
		setTimeout('$("#friends ul").fadeIn("slow");', 2000);	//animamos		;
		if(primeravez){
		$("#friendsup").hide();	//escondemos
		primeravez=false;
		}
		setTimeout('$("#friendsup").css({"display":"block"});', 2000);
		$('.menu1').css({'display':'block'});
		$('.menu4').css({'display':'block'});
		$(".menu1 a").css({'color':'white','text-decoration':'underline'});
		$(".menu5 a").css({'color':'#BDBDBD','cursor':'pointer','text-decoration':'none'});
		$(".menu2 a").css({'color':'#BDBDBD','cursor':'pointer','text-decoration':'none'});
		$(".menu3 a").css({'color':'#BDBDBD','cursor':'pointer','text-decoration':'none'});
		$(".menu4 a").css({'color':'#BDBDBD','cursor':'pointer','text-decoration':'none'});
		setTimeout('$("#search").fadeIn("slow");', 2000);
			//borramos todo lo dem�s
		$('#chat').css({'display':'none'});//pintamos en pantalla el chat	
		$('#log').val('');		//borramos textarea
		$('#logother').val(''); 	//borramos textarea
		$('.chatwithx.ui-li-link-alt.ui-btn ui-btn-up-e').CreateBubblePopup({	//creamos Bubble
			position : 'top',
			align	 : 'center',
			innerHtml: 'Call',
			innerHtmlStyle: {								
								background:'black',
								color:'#FFFFFF', 
								'text-align':'center'
							},	
			themeName: 	'bubble',
			themePath: 	'css/images/'
		});
		$('#register').css({'display':'none'});
		$('.menu2').fadeOut("slow");
		$('.menu5').fadeOut("slow");
		break;
		
	case 2: //pintamos chat
		ocupado=true;
		$('#chat').css({'display':'block'});//pintamos en pantalla el chat	
			//borramos todo lo dem�s
		$('#friends').css({'display':'none'});//quitamos en pantalla los amigos
		$("#friendsup").css({'display':'none'});
		$("#search").css({'display':'none'});
		$('#login').css({'display':'none'});
		$('#rmfriends').css({'display':'none'});
		$('#log').val('');		//borramos textarea
		$('#logother').val(''); 	//borramos texta7
	case 3: //hacemos desaparecer el chat y volvemos a Amigos	4444444444444444 
		
		break;
	case 4: //logout click
		ocupado=true;
		loginsuccess=false;
		//borramos lo que no queremos
		$("#chat").css({'display':'none'});	
		$("#search").css({'display':'none'});
		$('#friendsup').css({'display':'none'});
		$('#friends').css({'display':'none'});
		$('#rmfriends').css({'display':'none'});
		//pintamos lo inicio login
		//$('#login').css({'display':'block'});
		$('#login').delay(1000).fadeIn('slow');
		$(".menu3").html('<p><a class="amenu">Login</a>'+'</p>');				
		$('#connect').button( "enable" );
		$('#disconnect').attr('disabled', 'disabled');		
		$(".menu3 a").css({'color':'white','text-decoration':'underline','cursor':'pointer'});
		$(".menu1 a").css({'color':'#BDBDBD','cursor':'pointer','text-decoration':'none'});
		$(".menu2 a").css({'color':'#BDBDBD','cursor':'pointer','text-decoration':'none'});
		$(".menu5 a").css({'color':'#BDBDBD','cursor':'pointer','text-decoration':'none'});
		$(".menu4 a").css({'color':'#BDBDBD','cursor':'pointer','text-decoration':'none'});
		$('#register').css({'display':'none'});
		$('.menu2').delay(1000).fadeIn("slow");
		$('.menu5').delay(1000).fadeIn("slow");
		$('.menu1').css({'display':'none'});
		$('.menu4').css({'display':'none'});
		
		break;
	case 5: //pintamos listview search		 
			
		$("#resultsearch").css({"display":"block"});		
		$("#resultsearch ul").hide();	//escondemos			
		$("#resultsearch ul").listview();
		$("#resultsearch ul").css({'padding': '.8em 3px .5em 35px'});	
		$("#resultsearch ul").fadeIn("slow");	//animamos		;
		$('.ui-icon.ui-icon-makefriend.ui-icon-shadow').CreateBubblePopup({	//creamos Bubble
			position : 'top',
			align	 : 'center',
			innerHtml: 'Make Friend',
			innerHtmlStyle: {								
								background:'black',
								color:'#FFFFFF', 
								'text-align':'center'
							},	
			themeName: 	'bubble',
			themePath: 	'css/images/'
		});
							
				break;	
	case 6: //proceso de registrar
		$('#login').fadeOut('fast');
		//$('#register').css({'display':'block'});
		$('#register').delay(1000).fadeIn('slow');
		//$(".menu5 a").css({'color':'white','cursor':'pointer'});
		$(".menu5 a").css({'color':'white','text-decoration':'underline','cursor':'pointer'});
		$(".menu1 a").css({'color':'#BDBDBD','cursor':'pointer','text-decoration':'none'});
		$(".menu2 a").css({'color':'#BDBDBD','cursor':'pointer','text-decoration':'none'});
		$(".menu3 a").css({'color':'#BDBDBD','cursor':'pointer','text-decoration':'none'});
		$(".menu4 a").css({'color':'#BDBDBD','cursor':'pointer','text-decoration':'none'});
		break;
	case 7:
		//proceso de menu options para eliminar amigos
		$("#chat").css({'display':'none'});	
		$("#search").css({'display':'none'});
		$('#friendsup').css({'display':'none'});
		$('#friends').css({'display':'none'});		
		$('#rmfriends').css({'display':'block'});	
		$('#login').css({'display':'none'});
		$(".menu4 a").css({'color':'white','text-decoration':'underline','cursor':'pointer'});
		$(".menu1 a").css({'color':'#BDBDBD','cursor':'pointer','text-decoration':'none'});
		$(".menu2 a").css({'color':'#BDBDBD','cursor':'pointer','text-decoration':'none'});
		$(".menu3 a").css({'color':'#BDBDBD','cursor':'pointer','text-decoration':'none'});
		$(".menu5 a").css({'color':'#BDBDBD','cursor':'pointer','text-decoration':'none'});
		listview_make("rmfriends",friends,false);
		$("#rmfriends ul").hide();	//escondemos		
		$("#rmfriends ul").listview();
		$("#rmfriends ul").css({'padding': '.8em 3px .5em 35px'});	
		setTimeout('$("#rmfriends ul").fadeIn("slow");', 2000);	//animamos		;
		$("#friendsup").hide();	//escondemos
		setTimeout('$("#friendsup").css({"display":"block"});', 2000);
		
		$('.ui-icon.ui-icon-unmakefriend.ui-icon-shadow').CreateBubblePopup({	//creamos Bubble
			position : 'top',
			align	 : 'center',
			innerHtml: 'Unmake Friend',
			innerHtmlStyle: {								
								background:'black',
								color:'#FFFFFF', 
								'text-align':'center'
							},	
			themeName: 	'bubble',
			themePath: 	'css/images/'
		});
	}
	
	
	
}


/* Patrick
 * PopUp InfoCaller
 */
function Show_Popup(name) {
	var html="";
	name =  namereturn(name);
	$('#popup_content #aceptar').html("Accept call from "+name);
	$('#popup_content #denegar').html("Close call from "+name);
	$('#popup_content #aceptar').css({"font-size":"24pt"});
	$('#popup_content #denegar').css({"font-size":"24pt"});
		
	$('#popup_content #aceptar').click(function() {
		 Close_Popup();
		 ws.send("INVITE-OK#"+name+"#FROM#"+$('#name').val());
		ChatWith(name,true);//empezamos chat	
	});
	$('#popup_content #denegar').click(function() {
		 Close_Popup();
		 ws.send("BYE#"+name+"#FROM#"+$('#name').val());		
	});
	//$('#popup').fadeIn('fast');
	$('#window').fadeIn('slow');
	}

function Close_Popup() {
	//$('#popup').fadeOut('fast');
	$('#window').fadeOut('slow');
//	$('#popup_content #denegar').button("destroy");
	//$('#popup_content #aceptar').button("destroy");
	}


function menu_on(){
	$("ul a").css({'color':'#BDBDBD'});
	//Fix Errors - http://www.learningjquery.com/2009/01/quick-tip-prevent-animation-queue-buildup/
	
	//Remove outline from links
	$("a").click(function(){
		$(this).blur();
	});
	//$(".menu3 a").css({'color':'white','cursor':'pointer'});
	$(".menu3 a").css({'color':'white','text-decoration':'underline','cursor':'pointer'});
	$('.menu1').css({'display':'none'});
	$('.menu4').css({'display':'none'});
	//When mouse rolls over
	/*$(".menu1").mouseover(function(){
		$(this).stop().animate({height:'150px','z-index':'10'},{queue:false, duration:300});
	});
	
	//When mouse is removed
	$(".menu1").mouseout(function(){
		$(this).stop().animate({height:'50px'},{queue:false, duration:300});
	});
	$(".menu2").mouseover(function(){
		$(this).stop().animate({height:'150px','z-index':'10'},{queue:false, duration:300});
	});
	
	//When mouse is removed
	$(".menu2").mouseout(function(){
		$(this).stop().animate({height:'50px'},{queue:false, duration:300});
	});
	$(".menu3").mouseover(function(){
		$(this).stop().animate({height:'150px','z-index':'10'},{queue:false, duration:300});
	});
	$(".menu3 a").css({'color':'white'});
	
	//When mouse is removed
	$(".menu3").mouseout(function(){
		$(this).stop().animate({height:'50px'},{queue:false, duration:300});
	});
	$(".menu4").mouseover(function(){
		$(this).stop().animate({height:'150px','z-index':'10'},{queue:false, duration:300});
	});
	
	//When mouse is removed
	$(".menu4").mouseout(function(){
		$(this).stop().animate({height:'50px'},{queue:false, duration:300});
	});
	$(".menu5").mouseover(function(){
		$(this).stop().animate({height:'150px','z-index':'10'},{queue:false, duration:300});
	});
	
	//When mouse is removed
	$(".menu5").mouseout(function(){
		$(this).stop().animate({height:'50px'},{queue:false, duration:300});
	});*/
	
	$("#btnsearch").click(function(){
		devolver_submit($('#search_box').val());
	});
	$('#btnsearch').CreateBubblePopup({
		position : 'top',
		align	 : 'center',
		innerHtml: 'Find Friends',
		innerHtmlStyle: {			
							background:'black',
							color:'#FFFFFF', 
							'text-align':'center'
						},	
		themeName: 	'bubble',
		themePath: 	'css/images/'
	});

}

/*
 * Patrick 
 * - Devolver nombre correcto Jquery
 */
function namereturn(name){
	var namert="";
	if(getNodeType(name)=="HTMLCollection"){		
		namert=name[0].textContent;
		namert=namert.replace("Online","");
	}else if(getNodeType(name)=="HTMLLIElement"){		
		namert=name.textContent;
		namert=namert.replace("Online","");
	}else{
		namert = name;
		namert=namert.replace("Online","");
	}
	return namert;
}


/*
 * Patrick
 * Search function users
 */
function devolver_submit(busqueda){
	//alert("not implemented yet");
	ws.send("SEARCH#"+busqueda+"#FROM#"+$('#name').val());	
}
/*function delay(milisegundos){
for(i=0;i<=milisegundos;i++){
		setTimeout('return 0',1);
		}
}*/
/* $("sendForm").observe("submit", function(e) {
e.stop();
if (ws) {
    var textField = $("textField");
    ws.send(textField.value);
    log("[WebSocket#send]      Send:    '" + textField.value + "'\n");
   // textField.value = "";
    textField.focus();
}
});*/